<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input v-model="serchMoudle.username" clearable placeholder="请输入用户名" @clear="clear('user')" /></el-col>
          <el-col :span="6">
            <el-input v-model="serchMoudle.phone" clearable placeholder="请输入电话" @clear="clear('phone')" />
          </el-col>
          <el-col :span="8">
            <el-button type="primary" icon="el-icon-search" @click="getList">搜索</el-button>
            <el-button type="info" icon="el-icon-refresh" @click="resetList">重置</el-button>
            <el-button type="primary" icon="el-icon-circle-plus" @click="saveUserUI(null)">新增</el-button>
          </el-col>
        </el-row>
      </div>
      <div class="text item">
        <el-table :data="tableData" stripe style="width: 100%">
          <el-table-column prop="date" label="#" width="80">
            <template slot-scope="scope">
              {{ (serchMoudle.pageNo - 1) * serchMoudle.pageSize + scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="id" label="用户id" width="80" />
          <el-table-column prop="username" label="用户名" width="180" />
          <el-table-column prop="phone" label="电话" width="180" />
          <el-table-column label="状态" width="100">
            <template slot-scope="scope">
              <el-switch
                :value="scope.row.status"
                :active-value="1"
                :inactive-value="0"
                inactive-color="#ff4949"
                active-color="#13ce66"
                @change="handlerSwitch(scope.row,$event)"
              />
            </template>
          </el-table-column>
          <el-table-column prop="email" label="电子邮件" />
          <el-table-column label="操作" width="180">
            <template slot-scope="scope">
              <el-button type="primary" icon="el-icon-edit" size="mini" circle @click="saveUserUI(scope.row.id)" />
              <el-button type="danger" icon="el-icon-delete" size="mini" circle @click="delUser(scope.row.id)" />
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
    <el-pagination
      :current-page="currentPage4"
      :page-sizes="[5, 10, 20, 50]"
      :page-size="serchMoudle.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <!-- 新增/编辑弹窗 -->

    <el-dialog :title="title" :visible.sync="dialogFormVisible" @close="clearUserForm">
      <el-form ref="userForm" :rules="rules" :model="userForm">
        <el-form-item label="用户名" :label-width="formLabelWidth" prop="username">
          <el-input v-model="userForm.username" autocomplete="off" />
        </el-form-item>
        <el-form-item v-if="userForm.id == null || userForm.id === undefined" label="用户密码" :label-width="formLabelWidth" prop="password">
          <el-input v-model="userForm.password" type="password" autocomplete="off" />
        </el-form-item>
        <el-form-item label="电话" :label-width="formLabelWidth" prop="phone">
          <el-input v-model="userForm.phone" autocomplete="off" />
        </el-form-item>
        <el-form-item label="用户角色" :label-width="formLabelWidth">
          <el-checkbox-group
            v-model="userForm.roleIdList"
            :max="2"
          >
            <el-checkbox v-for="role in roleList" :key="role.roleId" :label="role.roleId">{{ role.roleDesc }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="邮件" :label-width="formLabelWidth" prop="email">
          <el-input v-model="userForm.email" autocomplete="off" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveUser">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import userApi from '@/api/userManage'
import roleApi from '@/api/roleManage'
export default {
  name: 'UserList',
  components: {},
  data() {
    var checkAge = (rule, value, callback) => {
      const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
      if (!emailRegex.test(value)) {
        return callback(new Error('邮件格式错误'))
      }
      callback()
    }
    return {
      userForm: {
        roleIdList: []
      },
      title: '',
      dialogFormVisible: false,
      formLabelWidth: '120px',
      input: '',
      input1: '',
      total: 0,
      roleList: [],
      serchMoudle: {
        pageNo: 1,
        pageSize: 10
      },
      rules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 16, message: '长度在 3 到 16 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入用户密码', trigger: 'blur' },
          { min: 3, max: 16, message: '长度在 3 到 16 个字符', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { min: 1, max: 15, message: '长度在 1 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, validator: checkAge, trigger: 'blur' }
        ]
      },
      currentPage4: 1,
      tableData: []
    }
  },
  computed: {},
  watch: {},
  created() {
    this.getList()
    this.getRoleListAll()
  },
  methods: {
    getRoleListAll() {
      roleApi.getRoleListAll().then(res => {
        if (res.code === 20000) {
          this.roleList = res.data
        }
        console.log(this.roleList)
      })
    },
    delUser(id) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        userApi.deleteUser(id).then(res => {
          this.$message({
            message: res.message,
            type: 'success'
          })
          this.getList()
        })
      })
    },
    handlerSwitch(row, index) {
      row.status = index
      userApi.editUser(row).then(res => {
        this.$message({
          message: res.message,
          type: 'success'
        })
      })
    },
    saveUser() {
      this.$refs.userForm.validate((valid) => {
        if (valid) {
          userApi.saveUser(this.userForm).then(res => {
            this.$message({
              message: res.message,
              type: 'success'
            })
            this.dialogFormVisible = false
            this.getList()
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    clearUserForm() {
      this.userForm = {
        roleIdList: []
      }
      this.$refs.userForm.resetFields()
    },
    saveUserUI(id) {
      if (id == null || id === undefined) {
        this.title = '新增用户'
      } else {
        this.title = '编辑用户'
        userApi.getUserInfo(id).then(res => {
          this.userForm = res.data
        })
      }
      this.dialogFormVisible = true
    },
    clear(params) {
      console.log(params)
      if (params === 'phone') {
        this.serchMoudle.phone = ''
        this.getList()
      }
      if (params === 'user') {
        this.serchMoudle.user = ''
        this.getList()
      }
    },
    getList() {
      userApi.getUserList(this.serchMoudle).then(res => {
        console.log(res)
        this.total = res.data.total
        this.tableData = res.data.rows
      })
    },
    resetList() {
      this.serchMoudle.username = ''
      this.serchMoudle.phone = ''
      this.serchMoudle.pageNo = 1
      this.serchMoudle.pageSize = 10
      this.getList()
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.serchMoudle.pageSize = val
      this.getList()
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.serchMoudle.pageNo = val

      this.getList()
    }
  }
}
</script>

<style lang="scss" scoped>
.box-card {
  margin-bottom: 10px;
}

.el-dialog .el-input {
  width: 80%;
}
</style>
